//
//  ImportTheWalletViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2018/12/26.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "ImportTheWalletViewController.h"
#import "UITextView+WZB.h"
#import "WallectService.h"
#import "AESCrypt.h"
#import "CreatWalletViewController.h"
#import "EOSService.h"
#import "WebInfoViewController.h"
#import "WeChatActionSheet.h"
@interface ImportTheWalletViewController ()<UITextViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong) UITextView *privateTV;
@property (nonatomic,strong) UITextField *psw1;
@property (nonatomic,strong) UITextField *psw2;
@property (nonatomic,strong) UITextField *pswTip;
@property (nonatomic,strong) WallectService *wallectService;
@property (nonatomic,weak) XThemeFlatButton *improtBtn;
@property (nonatomic,assign) BOOL agree;
@property (nonatomic,copy) NSString * welletSystem;
@property (nonatomic,strong) EOSService * service;


@end

@implementation ImportTheWalletViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
//    self.privateTV.text = @"5JBe15cAn68bp4ffvFj6e23xz7bLDWQ4nCtat1CLQzRUj445LFk";
//    self.psw1.text = @"12345678";
//    self.psw2.text = @"12345678";
    self.welletSystem = kContractName_EOSIOTOKEN;
    [self action];
}

#pragma mark - action

- (void)action{
    kWeakSelf(self);
    [self.improtBtn addTapBlock:^(UIButton * _Nonnull btn) {
        if (![EOS_Key_Encode validateWif:weakself.privateTV.text]) {
            [weakself.view makeToast:XLocalized(@"私钥格式有误!")];
            return;
        }
        if (weakself.psw1.text.length < 8) {
            [weakself.view makeToast:XLocalized(@"密码最小长度为8位!")];
            return;
        }
        if (![weakself.psw1.text isEqualToString:weakself.psw2.text]) {
            [weakself.view makeToast:XLocalized(@"密码不一致!")];
            return;
        }
        [XAlertTool alertTitle:@"风险提示" message:@"如果您的设备已经越狱,请勿在此设备上导入或创建钱包,这将会有很大的安全风险" cancelAction:^{
        } sureAction:^{
            weakself.wallectService.publicKey = [EOS_Key_Encode eos_publicKey_with_wif:weakself.privateTV.text];
//            DLog(@"currentThread %@",[NSThread currentThread]);
            [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
            [weakself.wallectService getKeyAccountsComplete:^(NSString *errorMsg,NSArray*accountNames, BOOL isSuccess) {
                if (isSuccess) {
                    if (accountNames.count) {
                        if (accountNames.count == 1) {
                            NSString*account = [accountNames firstObject];
                            if (StrValid(account)) {
                                [weakself improtAccount:account];
                            }
                        }else{
                            WeChatActionSheet*sheet =  [WeChatActionSheet showActionSheet:@"请选择要导入的钱包" buttonTitles:accountNames];
                            sheet.function = ^(WeChatActionSheet *actionSheet, NSInteger index) {
                                if (index != WECHATCANCELINDEX) {
                                    NSString*account = [accountNames objectOrNilAtIndex:index];
                                    if (StrValid(account)) {
                                        [weakself improtAccount:account];
                                    }
                                }
                            };
                        }
                    }else{
                        [MBProgressHUD hideHUDForView:weakself.view];
                        [weakself.view makeToast:XLocalized(@"获取账号失败！请检查私钥")];
                    }
                }else{
                    [weakself.view makeToast:errorMsg];
                    [MBProgressHUD hideHUDForView:weakself.view];
                }
            }];
        }];
       
    }];
  
}

-(void)improtAccount:(NSString*)account{
    Wallet*wallet = [Wallet new];
    wallet.wallet_name = account;
    wallet.password_sha = [self.psw1.text sha256String];
    wallet.password_tip = self.pswTip.text;
    wallet.wallet_private_AES_key = [WalletTool encryptWalletPrivatekey:self.privateTV.text password:self.psw1.text];
    wallet.wallet_public_key = self.wallectService.publicKey;
    wallet.wallet_uid = [[NSString stringWithFormat:@"%@%@",account,self.wallectService.publicKey] sha256String];
    wallet.wallet_system = self.welletSystem;
    wallet.addTime = [TimeHelper getCurrentTimestamp];
    self.service.wallet = wallet;
    [self.service getAccountInfoComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
        [MBProgressHUD hideHUDForView:self.view];
        if (success) {
            if (self.service.permission.length) {
                BOOL success = [[XHDataBaseManager shareInstance]insertWalletToDB:wallet];
                if (success) {
                    [kAppWindow makeToast: XLocalized(@"导入成功!")];
                    [self backBtnClicked];
                }
            }else{
                [kAppWindow makeToast: XLocalized(@"权限错误，导入失败")];
            }
            
        }
    }];
}

- (void)setupUI{
    self.title = XLocalized(@"导入钱包");
    UILabel *tipLab = [UILabel new];
    tipLab.font = kBoldFont(16);
    tipLab.textColor = UIColorHex(333333);
    tipLab.text = XLocalized(@"个人私钥");
    [self.contentView addSubview:tipLab];
    [tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(kNormalSpace);
    }];
    self.privateTV = [UITextView new];
    self.privateTV.layer.cornerRadius = AdaptedWidth(10);
    self.privateTV.font = kDefaultFont(14);
    self.privateTV.backgroundColor = UIColorHex(#F7F7F7);
    self.privateTV.wzb_placeholder = XLocalized(@"请输入您的私钥");
    [self.contentView addSubview:self.privateTV];
    [self.privateTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(80));
        make.top.equalTo(tipLab.mas_bottom).offset(AdaptedWidth(15));
    }];
    UILabel *tipLab2 = [UILabel new];
    tipLab2.font = kBoldFont(16);
    tipLab2.textColor = UIColorHex(333333);
    tipLab2.text = XLocalized(@"设定密码(不少于8位)");
    [self.contentView addSubview:tipLab2];
    [tipLab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.privateTV.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
    }];
    self.psw1 = [UITextField new];
    self.psw1.secureTextEntry = YES;
    self.psw1.borderStyle = UITextBorderStyleNone;
    self.psw1.layer.cornerRadius = AdaptedWidth(10);
    self.psw1.backgroundColor = UIColorHex(#F7F7F7);
    self.psw1.placeholder = XLocalized(@"请输入您的密码");;
    self.psw1.font = kDefaultFont(14);
    UIView*letfV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.psw1.leftView = letfV;
    self.psw1.leftViewMode = UITextFieldViewModeAlways;
    self.psw1.delegate = self;
    [self.contentView addSubview:self.psw1];
    [self.psw1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipLab2.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    self.psw2 = [UITextField new];
    self.psw2.secureTextEntry = YES;
    self.psw2.borderStyle = UITextBorderStyleNone;
    self.psw2.layer.cornerRadius = AdaptedWidth(10);
    self.psw2.backgroundColor = UIColorHex(#F7F7F7);
    self.psw2.placeholder = XLocalized(@"请再次输入您的密码");;
    self.psw2.font = kDefaultFont(14);
    self.psw2.delegate = self;
    UIView*letfV1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.psw2.leftView = letfV1;
    self.psw2.leftViewMode = UITextFieldViewModeAlways;
    [self.contentView addSubview:self.psw2];
    [self.psw2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.psw1.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    
    UILabel *tipLab3 = [UILabel new];
    tipLab3.font = kBoldFont(16);
    tipLab3.textColor = UIColorHex(333333);
    tipLab3.text = XLocalized(@"设置密码提示（非必填项）");
    [self.contentView addSubview:tipLab3];
    [tipLab3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.psw2.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
    }];
    
    self.pswTip = [UITextField new];
    self.pswTip.borderStyle = UITextBorderStyleNone;
    self.pswTip.layer.cornerRadius = AdaptedWidth(10);
    self.pswTip.backgroundColor = UIColorHex(#F7F7F7);
    self.pswTip.placeholder = XLocalized(@"请输入您的密码提示");;
    self.pswTip.font = kDefaultFont(14);
    UIView*letfV2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.pswTip.leftView = letfV2;
    self.pswTip.leftViewMode = UITextFieldViewModeAlways;
    [self.contentView addSubview:self.pswTip];
    [self.pswTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipLab3.mas_bottom).offset(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    
//    corner_nomal
//    corner_select
    UIButton *btn = [UIButton new];
    [btn setImage:IMAGE_NAMED(@"corner_nomal") forState:UIControlStateNormal];
    [btn setImage:IMAGE_NAMED(@"corner_select") forState:UIControlStateSelected];
    [self.contentView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pswTip.mas_bottom).offset(AdaptedWidth(5));
        make.left.mas_equalTo(AdaptedWidth(10));
        make.size.mas_equalTo(CGSizeMake(AdaptedWidth(35), AdaptedWidth(35)));
    }];
    kWeakSelf(self);

    [btn addTapBlock:^(UIButton * _Nonnull btn) {
        btn.selected = !btn.selected;
        weakself.agree = !weakself.agree;
        [weakself importBtnEnable];
    }];
    YYLabel *agreementLab = [YYLabel new];
    NSString *read = XLocalized(@"我已仔细阅读并同意");
    NSString *terms = XLocalized(@"《服务协议》");
    NSString *or = XLocalized(@"及");
    NSString *terms1 = XLocalized(@"《隐私协议》");

    NSString *str =[NSString stringWithFormat:@"%@%@%@%@",read,terms,or,terms1];
    NSRange hightRange = [str rangeOfString:terms];
    NSMutableAttributedString *text  = [[NSMutableAttributedString alloc] initWithString:str];
    text.font = kDefaultFont(12);
    text.color = UIColorHex(333333);
    [text setUnderlineStyle:NSUnderlineStyleSingle range:hightRange];
    [text setTextHighlightRange:hightRange color:kColorMain backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        WebInfoViewController *vc = [WebInfoViewController new];
        vc.gotoURL =  @"https://htm.beesgame.io/#/serve";
        vc.title =  XLocalized(@"服务协议");
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    

    NSRange hightRange1 = [str rangeOfString:terms1];
    [text setUnderlineStyle:NSUnderlineStyleSingle range:hightRange1];
    [text setTextHighlightRange:hightRange1 color:kColorMain backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        WebInfoViewController *vc = [WebInfoViewController new];
        vc.gotoURL =  @"https://htm.beesgame.io/#/privacy";
        vc.title =  XLocalized(@"隐私协议");
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    agreementLab.attributedText = text;
    
    [self.contentView addSubview:agreementLab];
    [agreementLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(btn.mas_centerY);
        make.left.equalTo(btn.mas_right);
        make.right.mas_equalTo(kNormalSpace);
    }];
    
    XThemeFlatButton*importBtn = [XThemeFlatButton button];
    self.improtBtn = importBtn;
    [importBtn setTitle:XLocalized(@"导入钱包") forState:UIControlStateNormal];
    [self.contentView addSubview:importBtn];
    [importBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btn.mas_bottom).offset(AdaptedWidth(35));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(40));
    }];
    
    XThemeFlatButton*creatBtn = [XThemeFlatButton button];
    [creatBtn addTapBlock:^(UIButton * _Nonnull btn) {
        CreatWalletViewController *vc = [CreatWalletViewController new];
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    [creatBtn setTitle:XLocalized(@"创建钱包") forState:UIControlStateNormal];
    [self.contentView addSubview:creatBtn];
    [creatBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(importBtn.mas_bottom).offset(AdaptedWidth(18));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(40));
        make.bottom.mas_equalTo(-AdaptedWidth(50));
    }];
    self.improtBtn.enabled = NO;
    self.privateTV.delegate = self;
    self.psw1.delegate = self;
    self.psw2.delegate = self;
    [self.psw1 addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [self.psw2 addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];

}
- (void)importBtnEnable{
    self.improtBtn.enabled = self.privateTV.text.length && self.psw1.text.length && self.psw2.text.length && self.agree;
}
#pragma mark - textViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    [self importBtnEnable];
}

#pragma mark - textField
- (void)textChange:(UITextField*)textField{
    [self importBtnEnable];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return [RegularExp controllABC123WithString:textField.text inRange:range inputString:string];
}

- (WallectService*)wallectService{
    if (!_wallectService) {
        _wallectService = [WallectService new];
    }
    return _wallectService;
}

- (EOSService*)service{
    if (!_service) {
        _service = [EOSService new];
    }
    return _service;
}
@end
